package com.secneo.appshare.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.secneo.appshare.AppShareApplication;
import com.secneo.appshare.R;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.RemoteApi.AppRecom;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.common.Util;
import com.secneo.mp.api.database.DatabaseHelper;


public class ChooseUserActivity extends Activity
{
	private Button mLoginBtn;
	private GridView mFriendsGridView;
	private LinearLayout mProgressLinear;
	private GetFriendsThread mGetFrisThread;
	private FriendsAdapter friendAdapter;
	private int snsType;
	private CheckBox chooseUserFirstCheckBox,chooseUserSecondCheckBox;
	List<AppRecom> friendsList =new ArrayList<AppRecom>();
	int friendsNumber=0;
	private TextView chooseUserShareTextView,textMessageFeedsTextView;
    public Handler mHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case Constants.MSG_GET_FEEDS_NETWORK_ERROR:
					View view = ChooseUserActivity.this.findViewById(R.id.error_user_feeds);
					view.setVisibility(View.VISIBLE);
					mProgressLinear.setVisibility(View.INVISIBLE);
					break;
					
				case Constants.MSG_GET_FANS_FINISH:
					
					mProgressLinear.setVisibility(View.GONE);
					friendsList=mGetFrisThread.getTalkList();
					refreshGridView(mGetFrisThread.getTalkList());
					String chooseTypeString="";
					if(snsType==Constants.SNS_INDEX_SINA)//sina
					{
						chooseTypeString="新浪";
					}
					else if(snsType==Constants.SNS_INDEX_TENCENT)//tencent
					{
						chooseTypeString="腾讯";
					}
					else if(snsType==Constants.SNS_INDEX_RENREN)//renren
					{
						chooseTypeString="人人网";	
					}
					
					else if(snsType==Constants.SNS_INDEX_KAIXIN)//kaixin
					{
						chooseTypeString="开心网";
					}
					
					if(!"".equals(chooseTypeString))
					{
						String chooseString = getString(R.string.choose_user_share, String.valueOf(friendsList.size()),chooseTypeString);
						chooseUserShareTextView.setText(chooseString);
					}else
					{
						chooseUserShareTextView.setVisibility(View.INVISIBLE);
						if(snsType==0)
						{
						chooseUserFirstCheckBox.setChecked(true);
						chooseUserSecondCheckBox.setChecked(true);
						}else
						{
							chooseUserFirstCheckBox.setChecked(false);
							chooseUserSecondCheckBox.setChecked(false);
						}
					}
				
					break;
					
				case Constants.MSG_GET_FEEDICON_FINISH:
					mFriendsGridView.invalidateViews();
					break;
			}
			super.handleMessage(msg);
		}

	};
	
	public void refreshGridView(final List<AppRecom> friendsList)
	{
		if(friendsList.size()==0)
		{
			textMessageFeedsTextView.setText("您还没有好友加入安卓分享，赶快告诉他们吧！");
		}else
		{
			
		}
		friendAdapter = new FriendsAdapter(this, friendsList);
		mFriendsGridView.setVisibility(View.VISIBLE);
		mFriendsGridView.setNumColumns(4);
		mFriendsGridView.setAdapter(friendAdapter);
	
	}
	
	protected void onCreate(Bundle paramBundle)
	{
		super.onCreate(paramBundle);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.appshare_choose_user);

        Bundle bundle = getIntent().getExtras();
        snsType=bundle.getInt("sns_type");
		
        AppShareApplication.getInstance().addActivity(this);
		final String uid = LocalStore.getLocaleStoreInstance(this).getUid();
		mFriendsGridView = (GridView) findViewById(R.id.gridview_choose_user);
		mFriendsGridView.setOnItemClickListener(new FriendsGridViewItemClickListener());
		mProgressLinear = (LinearLayout) findViewById(R.id.progress_user_feeds);
		chooseUserFirstCheckBox= (CheckBox) findViewById(R.id.ChooseUserFirstCheckBox);
		chooseUserSecondCheckBox= (CheckBox) findViewById(R.id.ChooseUserSecondCheckBox);
		chooseUserShareTextView=(TextView)findViewById(R.id.ChooseUserShareTextView);
		textMessageFeedsTextView=(TextView)findViewById(R.id.TextMessageFeedsTextView);
		if(0==snsType)
		{
			chooseUserShareTextView.setVisibility(View.INVISIBLE);
		}else
		{
			chooseUserShareTextView.setVisibility(View.VISIBLE);
		}
		chooseUserFirstCheckBox.setChecked(true);
		chooseUserSecondCheckBox.setChecked(true);
		chooseUserFirstCheckBox.setEnabled(false);
		chooseUserSecondCheckBox.setEnabled(false);
		
		mLoginBtn = (Button) findViewById(R.id.chooseOk);
		mLoginBtn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				try
				{
					if(0==snsType){
						DatabaseHelper dh=new DatabaseHelper(ChooseUserActivity.this);
						dh.insertUserAppPopularityBycatagory(ChooseUserActivity.this,2049);
						dh.close();
					}
					else if(Constants.SNS_INDEX_SINA==snsType){
						DatabaseHelper dh=new DatabaseHelper(ChooseUserActivity.this);
						dh.insertUserAppPopularityBycatagory(ChooseUserActivity.this,2052);
						dh.close();
					}
					
					List<AppRecom> list = friendAdapter.getList();
					final List<String> uidList = new ArrayList<String>();
					for(int i=0; i<list.size(); i++)
					{
						if(list.get(i).app_type == 1)
							uidList.add(list.get(i).package_name);
					}
					
					Thread upFrisThread = new Thread() 
					{
						public void run()
						{
							RemoteApiImpl remoteApi = new RemoteApiImpl();
							boolean ret = remoteApi.uploadFollowedFriends(ChooseUserActivity.this, uid, uidList);
							Log.d("MyTag", "uploadFollowedFriends ret = "+ret);
						}
					};
					if(uidList.size()>0)
						upFrisThread.start();
					
				}catch (Exception e) {
					e.printStackTrace();
				}
				finally
				{
					Intent intent=new Intent();
					intent.setClass(ChooseUserActivity.this, MainActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
					startActivity(intent);
					finish();
				}
			}
		});
		
		mGetFrisThread = new GetFriendsThread(this, mHandler, uid, snsType);
		mGetFrisThread.start();
	}
	
	@Override
	protected void onDestroy() 
	{
		mGetFrisThread.stopRun();
		mFriendsGridView.setAdapter(null);
		if(friendAdapter != null)
		{
			friendAdapter.freeDrawable();
			friendAdapter=null;
		}
		
		super.onDestroy();
	}
	
	public class FriendsAdapter extends BaseAdapter
	{
		private List<AppRecom> appList;
		public FriendsAdapter(Context ctx, List<AppRecom> appList)
		{
			this.appList = appList;
		}
		
		public void freeDrawable()
		{
			for(int i=0; i<appList.size(); i++)
			{
				if (!appList.get(i).app_icon.contains("buildin") &&
						appList.get(i).app_icon_drawable != null)
				{
					BitmapDrawable a = (BitmapDrawable) appList.get(i).app_icon_drawable;
					if(a!=null && !a.getBitmap().isRecycled())
						a.getBitmap().recycle();
					appList.get(i).app_icon_drawable = null;
				}
			}
			System.gc();
		}
		
		public void setStatus(int index)
		{
			if(appList.get(index).app_type == 1)
				appList.get(index).app_type = 0;
			else
				appList.get(index).app_type = 1;
		}
		
		public List<AppRecom> getList()
		{
			return appList;
		}

		@Override
		public int getCount()
		{
			return appList.size();
		}

		@Override
		public Object getItem(int position)
		{
			return position;
		}

		@Override
		public long getItemId(int position)
		{
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			FeedItem feedItem;
			if (convertView == null) 
			{
				View v = LayoutInflater.from(ChooseUserActivity.this).inflate(R.layout.appshare_app_toplist_item, null);
				feedItem = new FeedItem();
				feedItem.mAppIcon = (ImageView)v.findViewById(R.id.ivAppIcon);
				feedItem.mAppName = (TextView)v.findViewById(R.id.tvAppName);
				feedItem.mIconBac = (ImageView)v.findViewById(R.id.FavorAppIcon);
				v.setTag(feedItem);
				convertView = v;
			} 
			else 
				feedItem = (FeedItem)convertView.getTag();
			
			AppRecom appInfo = appList.get(position);
			if (appInfo.app_icon_drawable == null)
				feedItem.mAppIcon.setImageResource(R.drawable.some_user);
			else 
				feedItem.mAppIcon.setImageDrawable(appInfo.app_icon_drawable);
			
			if(appInfo.app_type == 1)
				feedItem.mIconBac.setImageResource(R.drawable.user_ok);
			else
				feedItem.mIconBac.setImageResource(R.drawable.user_no);
			
			feedItem.mAppIcon.setScaleType(ImageView.ScaleType.FIT_XY);
			feedItem.mAppName.setText(appInfo.app_name);
			feedItem.mAppName.setTextColor(android.graphics.Color.BLACK);
			return convertView;
		}
	}
	
	class FeedItem {
		ImageView mAppIcon;
		ImageView mIconBac;
		TextView mAppName;
	}
	
	public class GetFriendsThread extends Thread
	{
		private Context ctx;
		private Handler handler;
		private String uid;
		private List<AppRecom> mTalkList;
		private int snsType;
		private boolean isStop;
		
		public synchronized void stopRun()
		{
			isStop = true;
			this.interrupt();
		}
		
		public GetFriendsThread(Context c, Handler handler, String uid, int snsType) 
		{
			this.handler = handler;
			this.uid = uid;
			this.ctx = c;
			this.isStop = false;
			this.snsType = snsType;
			mTalkList = null;
		}
		
		public List<AppRecom> getTalkList() 
		{
			return mTalkList;
		}
		
		public void run() 
		{
			try 
			{
				if(mTalkList == null)
					mTalkList = new ArrayList<AppRecom>();
				else
					mTalkList.clear();
				
				RemoteApiImpl remoteApi = new RemoteApiImpl();
				mTalkList = remoteApi.getFriendsList(ctx, uid, snsType);
				if (mTalkList == null || mTalkList.size() == 0) 
				{
					Message msg = new Message();
					msg.what = Constants.MSG_GET_FEEDS_NETWORK_ERROR;
					handler.sendMessage(msg);
					return;
				}
				
				Message msg = new Message();
				msg.what = Constants.MSG_GET_FANS_FINISH;
				handler.sendMessage(msg);
				
				for(int i = 0; i < mTalkList.size(); i++) 
				{
					if (isStop) 
						return;
					AppRecom app =  mTalkList.get(i);
					
					try
					{
						String user_url = app.app_icon;
						if(user_url.contains("buildin"))
							app.app_icon_drawable = Util.getDrawableFromAsset(ctx, user_url);
						else
							app.app_icon_drawable = Util.getDrawableFromCache(ctx, user_url);
					
					}catch(Exception ex) {
						Log.d("MyTag", "ChooseUserActivity: read icon error = "+ex.getMessage());
					}
					
					if (app.app_icon_drawable != null) 
					{
						Message iconmsg = new Message();
						iconmsg.what = Constants.MSG_GET_FEEDICON_FINISH;
						handler.sendMessage(iconmsg);
					}
				}
				
			} catch(Exception ex) {
				Log.d("MyTag", "GetFriendsThread error:"+ex.getMessage());
			}
		}
	}
	
	class FriendsGridViewItemClickListener implements OnItemClickListener 
	{
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
		{
			try  
			{
				
				friendAdapter.setStatus(position);
				friendAdapter.notifyDataSetChanged();
				for(int i=0;i<friendsList.size();i++)
				{
					if(friendsList.get(i).app_type==0)
					{
						friendsNumber=friendsNumber+1;
					}
				}
				
                if(friendsList.size()==friendsNumber)
					
				{
					chooseUserFirstCheckBox.setChecked(false);
					chooseUserSecondCheckBox.setChecked(false);
				}else
				{
					friendsNumber=0;
					chooseUserFirstCheckBox.setChecked(true);
					chooseUserSecondCheckBox.setChecked(true);
				}
				
			} catch(Exception ex) {
				ex.printStackTrace();
			}
			return;
		} 
	}
}
